//
//  AlbumViewController.m
//  DolphinMusic
//
//  Created by dllo on 15/3/27.
//  Copyright (c) 2015年 蓝鸥科技. All rights reserved.
//

#import "AlbumViewController.h"
#import "AudioTableViewCell.h"
#import "MusicPlayViewController.h"
#import "UIScrollView+MJRefresh.h"
#import "MJRefresh.h"

@interface AlbumViewController () <UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, retain)MBProgressHUD *HUD;
@property (nonatomic, retain)UITableView *tableView;
@property (nonatomic, retain)NSMutableArray *arr;
@property (nonatomic, retain)UIButton *leftButton;
@property (nonatomic, retain)NSString *trackCount;
@property (nonatomic, assign)BOOL ifCollect;
@property (nonatomic, retain)UIButton *collectButton;
@property (nonatomic, retain)NSString *nextPageAddress;
@property (nonatomic, assign)NSInteger page;
@property (nonatomic, retain)NSString *imageStr;

@end

@implementation AlbumViewController

- (void)dealloc
{
    [_imageStr release];
    [_albumID release];
    [_nextPageAddress release];
    [_collectButton release];
    [_HUD release];
    [_tableView release];
    [_arr release];
    [_leftButton release];
    [_trackCount release];
    [_address release];
    [_title11 release];
    [super dealloc];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = [UIColor whiteColor];
    UIView *view1 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, VIEW_WIDTH, 20)];
    view1.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:view1];
    [view1 release];
    
    self.HUD = [[MBProgressHUD alloc] initWithView:self.view];
    [self.view addSubview:self.HUD];
    self.HUD.labelText = @"客官请稍等...";
    self.HUD.dimBackground = YES;
    [self.HUD show:YES];
    
    self.leftButton = [UIButton buttonWithType:UIButtonTypeSystem];
    self.leftButton.frame = CGRectMake(0, 20, 50, 44);
    
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 12, 20, 20)];
    imageView.image = [UIImage imageNamed:@"backButton.png"];
    [self.leftButton addSubview:imageView];
    [imageView release];
    
//    [self.leftButton setBackgroundImage:[UIImage imageNamed:@"backButton.png"] forState:UIControlStateNormal];
    [self.leftButton addTarget:self action:@selector(leftButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.leftButton];
    

    self.page = 1;
    [NetHandler getDataWithUrl:self.address completion:^(id dict) {
        [self setPageWithData:dict];
    }];
    
}

- (void)pullAction
{
    self.page++;
    self.nextPageAddress = [NSString stringWithFormat:@"http://mobile.ximalaya.com/mobile/others/ca/album/track/%@/true/%ld/15", self.albumID, self.page];
    
    
    [NetHandler getDataWithUrl:self.nextPageAddress completion:^(id dict) {
        NSArray *arr1 = [[dict objectForKey:@"tracks"] objectForKey:@"list"];
        if (arr1.count != 0) {
            
        for (NSDictionary *dic in arr1) {
            Audio *audio = [[Audio alloc] initWithDictionary:dic];
            [self.arr addObject:audio];
            [audio release];
        }
            [self.tableView reloadData];
            [self.tableView.footer endRefreshing];
        }
        else {
            self.tableView.footer.state = MJRefreshFooterStateNoMoreData;
        }
        
    }];
    
    
}

- (void)setPageWithData:(id)dict
{
    self.arr = [NSMutableArray array];
    NSArray *arr1 = [[dict objectForKey:@"tracks"] objectForKey:@"list"];
    if ([arr1 isKindOfClass:[NSArray class]]) {
    for (NSDictionary *dic in arr1) {
        Audio *audio = [[Audio alloc] initWithDictionary:dic];
        [self.arr addObject:audio];
        [audio release];
    }
    }
    
    self.trackCount = [[[dict objectForKey:@"tracks"] objectForKey:@"totalCount"] stringValue];
    
    NSString *imageStr = [[dict objectForKey:@"album"] objectForKey:@"coverWebLarge"];
    UIImageView *imageView1 = [[UIImageView alloc] initWithFrame:CGRectMake(0, 20, VIEW_WIDTH, VIEW_WIDTH)];
    [imageView1 setImageWithURL:[NSURL URLWithString:[imageStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]];
    [self.view addSubview:imageView1];
    [imageView1 release];
    
    UIImageView *imageView11 = [[UIImageView alloc] initWithFrame:imageView1.frame];
    imageView11.image = [UIImage imageNamed:@"menglong.jpg"];
    imageView11.alpha = 0.9;
    [self.view addSubview:imageView11];
    [imageView11 release];
    
    [self.view bringSubviewToFront:self.leftButton];
    
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 20, VIEW_WIDTH, VIEW_HEIGHT - 20 - (70.0 / 667) * VIEW_HEIGHT) style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.rowHeight = 110;
    self.tableView.backgroundColor = [UIColor clearColor];
    self.tableView.showsVerticalScrollIndicator = NO;
    
    [self.tableView addLegendFooterWithRefreshingTarget:self refreshingAction:@selector(pullAction)];
    
    [self.tableView registerClass:[AudioTableViewCell class] forCellReuseIdentifier:@"audioReuse"];
    [self.view addSubview:self.tableView];
    [_tableView release];
    
    
    NSDictionary *dic = [dict objectForKey:@"album"];
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, VIEW_WIDTH, 220)];
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(40, 0, VIEW_WIDTH - 80, 50)];
    titleLabel.font = [UIFont systemFontOfSize:19];
    titleLabel.text = [dic objectForKey:@"title"];
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.textColor = [UIColor whiteColor];
    [headerView addSubview:titleLabel];
    [titleLabel release];
    
    UIImageView *imageView21 = [[UIImageView alloc] initWithFrame:CGRectMake(20, 90, 100, 100)];
    [imageView21 setImageWithURL:[NSURL URLWithString:[imageStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]];
    [headerView addSubview:imageView21];
    [imageView21 release];
    
    UIImageView *authorImageView = [[UIImageView alloc] initWithFrame:CGRectMake(130, 90, 40, 40)];
    authorImageView.layer.cornerRadius = 20;
    authorImageView.layer.masksToBounds = YES;
    self.imageStr = [dic objectForKey:@"avatarPath"];
    [authorImageView setImageWithURL:[NSURL URLWithString:[self.imageStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]];
    [headerView addSubview:authorImageView];
    [authorImageView release];
    
    UILabel *authorLabel = [[UILabel alloc] initWithFrame:CGRectMake(180, 95, VIEW_WIDTH - 170 - 10, 40)];
    authorLabel.textColor = [UIColor whiteColor];
    authorLabel.text = [dic objectForKey:@"nickname"];
    [headerView addSubview:authorLabel];
    [authorLabel release];
    
    UILabel *tagLabel = [[UILabel alloc] initWithFrame:CGRectMake(130, 130, VIEW_WIDTH - 130, 40)];
    NSString *tags = [dic objectForKey:@"tags"];
    NSArray *tagArr = [tags componentsSeparatedByString:@","];
    NSString *tag = [tagArr firstObject];
    for (NSInteger i = 1; i < tagArr.count; i++) {
        tag = [NSString stringWithFormat:@"%@  %@", tag, tagArr[i]];
    }
    tagLabel.font = [UIFont systemFontOfSize:15];
    tagLabel.text = tag;
    tagLabel.textColor = [UIColor whiteColor];
    
    [headerView addSubview:tagLabel];
    [tagLabel release];
    
    
    UILabel *countLabel = [[UILabel alloc] initWithFrame:CGRectMake(130, 170, 80, 20)];
    NSString *count = [[dic objectForKey:@"tracks"] stringValue];
    count = [NSString stringWithFormat:@"声音( %@ )", count];
    countLabel.textColor = [UIColor whiteColor];
    countLabel.text = count;
    countLabel.font = [UIFont systemFontOfSize:15];
    [headerView addSubview:countLabel];
    [countLabel release];
    
    self.collectButton = [UIButton buttonWithType:UIButtonTypeSystem];
    self.collectButton.frame = CGRectMake(250, 170, 25, 25);
    
    DataBaseHandler *dbHandler = [DataBaseHandler shareInstance];
    NSMutableArray *collectionArr = [dbHandler selectAllInFMalbumCollection];
    
    [self.collectButton setBackgroundImage:[UIImage imageNamed:@"fmweishoucang"] forState:UIControlStateNormal];
    
    for (FMAlbum *album in collectionArr) {
        if ([album.albumID isEqualToString:self.albumID]) {
            [self.collectButton setBackgroundImage:[UIImage imageNamed:@"fmyishoucang"] forState:UIControlStateNormal];
            self.ifCollect = YES;
        }
    }
    
    [self.collectButton addTarget:self action:@selector(collectionButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    
    [headerView addSubview:self.collectButton];
    
    
    self.tableView.tableHeaderView = headerView;
    [headerView release];
    
    [self.view addSubview:self.leftButton];
    
    
    [self.HUD hide:YES];
    
}

- (void)collectionButtonAction:(UIButton *)button
{
    DataBaseHandler *dbHandler = [DataBaseHandler shareInstance];
    
    self.ifCollect = !self.ifCollect;
    
    self.album = [[FMAlbum alloc] init];
    self.album.albumID = self.albumID;
    self.album.albumCoverUrl290 = self.imageStr;
    self.album.title = self.title11;
    
    if (self.ifCollect == YES) {
        
        [dbHandler insertFMalbum:self.album];
        
        [self.collectButton setBackgroundImage:[UIImage imageNamed:@"fmyishoucang"] forState:UIControlStateNormal];
    }
    else {
        [dbHandler deleteFMalbum:self.album];
        [self.collectButton setBackgroundImage:[UIImage imageNamed:@"fmweishoucang"] forState:UIControlStateNormal];
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.arr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    AudioTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"audioReuse" forIndexPath:indexPath];
    cell.audio = [self.arr objectAtIndex:indexPath.row];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    Audio *audio = [self.arr objectAtIndex:indexPath.row];
    MusicPlayViewController *musicPlayVC = [MusicPlayViewController shareInstance];
    
    musicPlayVC.type = @"FM";
    
    musicPlayVC.address = [NSString stringWithFormat:@"http://mobile.ximalaya.com/mobile/track/detail?device=android&trackId=%@", audio.audioId];
    
    musicPlayVC.songID = audio.audioId;
}


- (void)leftButtonAction:(UIButton *)button
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)viewWillAppear:(BOOL)animated
{
    UIWindow *window = [[UIApplication sharedApplication] keyWindow];
    UIButton *button = (UIButton *)[window viewWithTag:1000];
    button.hidden = YES;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
